package br.net.woodstock.tickettoride.samples.web1;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.net.woodstock.tickettoride.client.TicketHash;
import br.net.woodstock.tickettoride.client.TicketRequest;
import br.net.woodstock.tickettoride.client.TicketSession;
import br.net.woodstock.tickettoride.client.beans.DefaultTicketRequest;
import br.net.woodstock.tickettoride.client.beans.ServletRequestConverter;
import br.net.woodstock.tickettoride.client.jdk6.TicketSessionHolder;

public class TicketServlet extends HttpServlet {

	private static final long	serialVersionUID	= 1L;

	@Override
	protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		this.doAll(request, response);
	}

	@Override
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		this.doAll(request, response);
	}

	private void doAll(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		ServletRequestConverter converter = new ServletRequestConverter();
		byte[] data = converter.toBytes(request);
		TicketSession session = TicketSessionHolder.getInstance().getSession();
		TicketRequest ticketRequest = new DefaultTicketRequest("sample2", Integer.valueOf(10), data);
		TicketHash hash = session.send(ticketRequest);
		request.setAttribute("hash", hash.toString());

		request.getRequestDispatcher("/index.jsp").include(request, response);
	}

}
